package cn.com.csg.smartenergy.modules.biz.task.core;

import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.config.CronTask;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
 * @program: simple-demo
 * @description: 添加定时任务注册类，用来增加、删除定时任务。
 * @author: WJJ
 * @date: 2022/5/05
 **/
@Component
public class CronTaskRegistrar implements DisposableBean {
    private final Map<String, ScheduledTask> scheduledTasks = new ConcurrentHashMap<>(16);
    @Autowired
    private TaskScheduler taskScheduler;
    public TaskScheduler getScheduler() {
        return this.taskScheduler;
    }

    /**
     * 获取所有定时任务
     * @return
     */
    public Map<String, ScheduledTask> getAllTasks() {
        return this.scheduledTasks;
    }
    /**
     * 新增定时任务
     * @param task
     * @param cronExpression
     */
    public void addCronTask(String jobId,Runnable task, String cronExpression) {
        addCronTask(jobId,new CronTask(task, cronExpression));
    }
    public void addCronTask(String jobId,CronTask cronTask) {
        if (cronTask != null) {
            Runnable task = cronTask.getRunnable();
            if (this.scheduledTasks.containsKey(jobId)) {
                removeCronTask(jobId);
            }
            this.scheduledTasks.put(jobId, scheduleCronTask(cronTask));
        }
    }
    /**
     * 移除定时任务
     * @param jobId
     */
    public void removeCronTask(String jobId) {
        ScheduledTask scheduledTask = this.scheduledTasks.remove(jobId);
        if (scheduledTask != null)
            scheduledTask.cancel();
    }
    public ScheduledTask scheduleCronTask(CronTask cronTask) {
        ScheduledTask scheduledTask = new ScheduledTask();
        scheduledTask.future = this.taskScheduler.schedule(cronTask.getRunnable(), cronTask.getTrigger());
        return scheduledTask;
    }
    @Override
    public void destroy() {
        for (ScheduledTask task : this.scheduledTasks.values()) {
            task.cancel();
        }
        this.scheduledTasks.clear();
    }
}
